//
//  AppDelegate.m
//  GameBaby
//
//  Created by keyZhang on 13-12-19.
//  Copyright (c) 2013年 keyZhang. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "OpenUDID.h"
#import "DataService.h"
#import "ShareEngine.h"
#import "sys/sysctl.h"
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [NSThread sleepForTimeInterval:.5];
//    检测是否有版本更新
    __weak AppDelegate *this = self;
    [DataService requestWithURL:[NSURL URLWithString:@"http://m.a.ewoka.com/server"]
                         params:nil
                     httpMethod:@"GET"
                    finishBlock:^(id result) {
                        [this finishVersionData:result];
                    }];
    
//  获得appid请求信息
    [[ShareEngine sharedInstance] registerApp];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    NSString *appIdentifier = [OpenUDID value];
    [[NSUserDefaults standardUserDefaults] setObject:appIdentifier forKey:@"appid"];
    NSString *urlStr = [NSString stringWithFormat:@"http://m.a.ewoka.com/user"];
    NSString *devicePlatForm = [self doDevicePlatform];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:appIdentifier,@"appid",devicePlatForm,@"client", nil];
    [DataService requestWithURL:urlStr
                         params:dic
                     httpMethod:@"POST"
                    finishBlock:^(id result) {
                        [this loadDataFinished:result];
                    }];
    
//    判断是不是第一次启动
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
        NSLog(@"第一次启动");
    }else{
        NSLog(@"不是第一次启动");
    }

    BaseTabBarController *baseTabBar = [[BaseTabBarController alloc]init];
    self.window.rootViewController = baseTabBar;
    
    return YES;
}

//返回版本信息
- (void)finishVersionData:(NSDictionary *)result
{
//    返回的参数信息
    NSString *latestVersion = [result objectForKey:@"version"];
    self.trackViewUrl = [result objectForKey:@"url"];
    NSString *trackName = @"E蜗卡";
    NSString *upMessage = [result objectForKey:@"update_msg"];
    double doubleUpdateVersion = [latestVersion doubleValue];
//    系统的版本信息
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDict objectForKey:@"CFBundleVersion"];
    double doubleCurrentVersion = [currentVersion doubleValue];
//    比较版本是否相同
    if (doubleCurrentVersion < doubleUpdateVersion) {
        UIAlertView *alert;
        alert = [[UIAlertView alloc] initWithTitle:trackName
                                           message:upMessage
                                          delegate: self
                                 cancelButtonTitle:@"取消"
                                 otherButtonTitles: @"升级", nil];
        [alert show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.trackViewUrl]];
    }
}

//返回用户数据
- (void)loadDataFinished:(NSDictionary *)result
{
    NSLog(@"%@",result);
    [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"uid"] forKey:@"uid"];
    [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"username"] forKey:@"username"];
    [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"wnd"] forKey:@"wnd"];
    [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"is_complete"] forKey:@"is_complete"];
    [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"is_web_login"] forKey:@"is_web_login"];
    [[NSUserDefaults standardUserDefaults] setObject:[result objectForKey:@"is_sign"] forKey:@"is_sign"];
//    保存头像
    NSData *data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:[result objectForKey:@"avatar"]]];
    [[NSUserDefaults standardUserDefaults] setObject:data1 forKey:@"headImgData"];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [[ShareEngine sharedInstance] handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [[ShareEngine sharedInstance] handleOpenURL:url];
}

- (NSString*) doDevicePlatform
{
    size_t size;
    int nR = sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = (char *)malloc(size);
    nR = sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"]) {
        
        platform = @"iPhone";
        
    } else if ([platform isEqualToString:@"iPhone1,2"]) {
        
        platform = @"iPhone 3G";
        
    } else if ([platform isEqualToString:@"iPhone2,1"]) {
        
        platform = @"iPhone 3GS";
        
    } else if ([platform isEqualToString:@"iPhone3,1"]||[platform isEqualToString:@"iPhone3,2"]||[platform isEqualToString:@"iPhone3,3"]) {
        
        platform = @"iPhone 4";
        
    } else if ([platform isEqualToString:@"iPhone4,1"]) {
        
        platform = @"iPhone 4S";
        
    } else if ([platform isEqualToString:@"iPhone5,1"]||[platform isEqualToString:@"iPhone5,2"]) {
        
        platform = @"iPhone 5";
        
    }else if ([platform isEqualToString:@"iPhone5,3"]||[platform isEqualToString:@"iPhone5,4"]) {
        
        platform = @"iPhone 5C";
        
    }else if ([platform isEqualToString:@"iPhone6,2"]||[platform isEqualToString:@"iPhone6,1"]) {
        
        platform = @"iPhone 5S";
        
    }else if ([platform isEqualToString:@"iPod4,1"]) {
        
        platform = @"iPod touch 4";
        
    }else if ([platform isEqualToString:@"iPod5,1"]) {
        
        platform = @"iPod touch 5";
        
    }else if ([platform isEqualToString:@"iPod3,1"]) {
        
        platform = @"iPod touch 3";
        
    }else if ([platform isEqualToString:@"iPod2,1"]) {
        
        platform = @"iPod touch 2";
        
    }else if ([platform isEqualToString:@"iPod1,1"]) {
        
        platform = @"iPod touch";
        
    } else if ([platform isEqualToString:@"iPad3,2"]||[platform isEqualToString:@"iPad3,1"]) {
        
        platform = @"iPad 3";
        
    } else if ([platform isEqualToString:@"iPad2,2"]||[platform isEqualToString:@"iPad2,1"]||[platform isEqualToString:@"iPad2,3"]||[platform isEqualToString:@"iPad2,4"]) {
        
        platform = @"iPad 2";
        
    }else if ([platform isEqualToString:@"iPad1,1"]) {
        
        platform = @"iPad 1";
        
    }else if ([platform isEqualToString:@"iPad2,5"]||[platform isEqualToString:@"iPad2,6"]||[platform isEqualToString:@"iPad2,7"]) {
        
        platform = @"ipad mini";
        
    } else if ([platform isEqualToString:@"iPad3,3"]||[platform isEqualToString:@"iPad3,4"]||[platform isEqualToString:@"iPad3,5"]||[platform isEqualToString:@"iPad3,6"]) {
        
        platform = @"ipad 3";
        
    }
    
    return platform;
}

@end
